package com.company.cloud.user.modules.app.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.company.cloud.common.constant.BaseConstant;
//import com.company.cloud.dis.modules.api.request.DistributorClientAddParam;
//import com.company.cloud.dis.modules.api.service.DisRemoteService;
import com.company.cloud.user.constant.*;
import com.company.cloud.user.modules.api.constant.UserRegisterWayEnum;
import com.company.cloud.user.modules.app.service.UserAppService;
import com.company.cloud.user.modules.base.entity.*;
import com.company.cloud.user.modules.base.service.*;
import com.company.common.server.config.cloud.ProjectConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.common.utils.PasswordUtils;
import com.company.cloud.common.utils.StrSplitUtils;
import com.company.cloud.user.modules.api.request.UserRegisterParam;
import com.company.cloud.user.modules.app.service.UserRegisterService;

import cn.hutool.core.util.IdUtil;

@Service
public class UserRegisterServiceImpl implements UserRegisterService {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UserRoleInfoService userRoleInfoService;

    @Autowired
    private UserShareCodeService userShareCodeService;

    @Autowired
    private ThirdUserInfoService thirdUserInfoService;

    @Autowired
    private UserAppService userAppService;

    @Autowired
    private UserInvitationInfoService userInvitationInfoService;

    @Autowired
    private TeamUserInfoService teamUserInfoService;

    @Autowired
    private ProjectConfig projectConfig;

    //todo
//	@Autowired
//	private DisRemoteService disRemoteService;

    /***/
    private void validate(UserRegisterParam param) {
        ValidatorUtils.validate(param);
    }

    /***/
    private void check_only(UserRegisterParam param) {
        if (UserRegisterWayEnum.Reg_Mobile.getCode().equals(param.getRegWay())) { //手机
            if (StringUtils.isEmpty(param.getMobile())) {
                throw new BusinessException(ErrorUserEnum.USER_MOBILE_NULL);
            }
            //验证手机号唯一
            int count = userInfoService.count(new QueryWrapper<UserInfo>()
                    .eq(projectConfig.isCompanyPattern(), "company_no", param.getCompanyNo())
                    .eq("mobile", param.getMobile())
            );
            if (count > 0) {
                throw new BusinessException(ErrorUserEnum.USER_MOBILE_EXISTS);
            }
            param.setUserName(param.getMobile());
        } else if (UserRegisterWayEnum.Reg_Mail.getCode().equals(param.getRegWay())) {  //邮箱
            if (StringUtils.isEmpty(param.getEmail())) {
                throw new BusinessException(ErrorUserEnum.USER_MAIL_NULL);
            }
            //验证邮箱唯一
            int count = userInfoService.count(new QueryWrapper<UserInfo>()
                    .eq(projectConfig.isCompanyPattern(), "company_no", param.getCompanyNo())
                    .eq("email", param.getEmail()));
            if (count > 0) {
                throw new BusinessException(ErrorUserEnum.USER_MAIL_EXISTS);
            }
            param.setUserName(param.getEmail());
        } else if (UserRegisterWayEnum.Reg_UserName.getCode().equals(param.getRegWay())) { //用户名
            if (StringUtils.isEmpty(param.getUserName())) {
                throw new BusinessException(ErrorUserEnum.USER_USERNAME_NULL);
            }
            //验证用户名唯一 用户名全系统唯一
            int count = userInfoService.count(new QueryWrapper<UserInfo>()
                    .eq("user_name", param.getUserName()));
            if (count > 0) {
                throw new BusinessException(ErrorUserEnum.USER_USERNAME_EXISTS);
            }
        } else if (UserRegisterWayEnum.Reg_Mobile_UserName.getCode().equals(param.getRegWay())) { //用户名和手机号
            if (StringUtils.isEmpty(param.getUserName())) {
                throw new BusinessException(ErrorUserEnum.USER_USERNAME_NULL);
            }
            if (StringUtils.isEmpty(param.getMobile())) {
                throw new BusinessException(ErrorUserEnum.USER_MOBILE_NULL);
            }
            //验证用户名唯一 用户名全系统唯一
            int count = userInfoService.count(new QueryWrapper<UserInfo>()
                    .eq("user_name", param.getUserName()));
            if (count > 0) {
                throw new BusinessException(ErrorUserEnum.USER_USERNAME_EXISTS);
            }
            //验证手机号唯一
            int count2 = userInfoService.count(new QueryWrapper<UserInfo>()
                    .eq(projectConfig.isCompanyPattern(), "company_no", param.getCompanyNo())
                    .eq("mobile", param.getMobile())
            );
            if (count2 > 0) {
                throw new BusinessException(ErrorUserEnum.USER_MOBILE_EXISTS);
            }
        }
    }

    @Override
    @Transactional
    public UserInfo register(UserRegisterParam param, LoginSimpleUserInfo loginUserInfo) {
        this.validate(param);
        this.check_only(param);
        //推荐码
        String referralCode = null;
        Integer referralUserId = null;
        if (StringUtils.hasText(param.getReferralCode())) {
            referralCode = param.getReferralCode();
            UserShareCode uscInfo = userShareCodeService.getOne(new QueryWrapper<UserShareCode>()
                    .eq(projectConfig.isCompanyPattern(), "company_no", param.getCompanyNo())
                    .eq("share_code", param.getReferralCode()));
            if (uscInfo != null) {
                referralUserId = uscInfo.getUserId();
            }
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setCompanyNo(param.getCompanyNo());
        userInfo.setUserTypeOne(param.getUserTypeOne());
        userInfo.setUserTypeTwo(param.getUserTypeTwo());
        userInfo.setSourceOne(param.getSourceOne());
        userInfo.setSourceTwo(param.getSourceTwo());
        userInfo.setUserName(param.getUserName());
        userInfo.setNickName(param.getNickName());
        userInfo.setUserState(UserStateEnum.NORMAL.getCode());
        userInfo.setNationCode(param.getNationCode());
        userInfo.setMobile(param.getMobile());
        userInfo.setEmail(param.getEmail());
        userInfo.setHeadImg(param.getHeadImg());
        if (!StringUtils.isEmpty(param.getPassword())) {
            String[] passwords = PasswordUtils.getMd5Password(param.getPassword());
            userInfo.setPassword(passwords[0]);
            userInfo.setSalt(passwords[1]);
        }
        userInfo.setReferralCode(referralCode);
        userInfo.setReferralUserId(referralUserId);
        userInfo.setShareCode(IdUtil.getSnowflake(2, 2).nextIdStr());
        userInfo.setRegTime(LocalDateTime.now());
        userInfo.setRegIp(param.getRegIp());
        userInfo.setRegClientType(param.getClientType());
        userInfo.setRegDeviceNo(param.getClientDeviceNo());
        userInfo.setLlType(param.getLlType());
        userInfo.setLongitude(param.getLongitude());
        userInfo.setLatitude(param.getLatitude());
        userInfo.setUserTags(StrSplitUtils.list2string(param.getUserTags()));
        userInfo.setCdt(LocalDateTime.now());
        userInfo.setCip(param.getRegIp());
        userInfo.setCman(userInfo.getUserName());
        //员工
        userInfo.setTel(param.getTel());
        userInfo.setQq(param.getQq());
        userInfo.setDeptId(param.getDeptId());
        userInfo.setIsDeptManager(param.getIsDeptManager());
        userInfo.setDataAuthorityType(param.getDataAuthorityType());
        userInfo.setDataAuthorityScope(StrSplitUtils.list2string(param.getDataAuthorityScope()));
        userInfo.setJobCode(StrSplitUtils.list2string(param.getJobCode()));
        userInfo.setIsManager(param.getIsManager());
        userInfo.setCustType(param.getCustType());
        userInfo.setCustCode(param.getCustCode());
        userInfo.setCustName(param.getCustName());
        userInfoService.save(userInfo);
        //分享码
        UserShareCode shareCodeEntity = new UserShareCode();
        shareCodeEntity.setCompanyNo(param.getCompanyNo());
        shareCodeEntity.setUserId(userInfo.getId());
        shareCodeEntity.setShareCode(userInfo.getShareCode());
        shareCodeEntity.setCdt(LocalDateTime.now());
        shareCodeEntity.setCip(param.getRegIp());
        shareCodeEntity.setCman(userInfo.getId());
        userShareCodeService.save(shareCodeEntity);
        // 角色关联关系
        if (!CollectionUtils.isEmpty(param.getRoles())) {
            List<UserRoleInfo> comUserRoleInfos = new ArrayList<UserRoleInfo>();
            for (String roleCode : param.getRoles()) {
                if (roleCode != null && !"".equals(roleCode)) {
                    UserRoleInfo userRoleInfo = new UserRoleInfo();
                    userRoleInfo.setCompanyNo(userInfo.getCompanyNo());
                    userRoleInfo.setUserId(userInfo.getId());
                    userRoleInfo.setRoleCode(roleCode);
                    if (loginUserInfo != null) {
                        userRoleInfo.addCreateParam(loginUserInfo);
                        userRoleInfo.addEditParam(loginUserInfo);
                    } else {
                        userRoleInfo.setCdt(LocalDateTime.now());
                        userRoleInfo.setCip(userInfo.getRegIp());
                        userRoleInfo.setCman(userInfo.getId());
                        userRoleInfo.setEdt(LocalDateTime.now());
                        userRoleInfo.setEip(userInfo.getRegIp());
                        userRoleInfo.setEman(userInfo.getId());
                    }
                    comUserRoleInfos.add(userRoleInfo);
                }
            }
            if (comUserRoleInfos.size() > 0) {
                userRoleInfoService.saveBatch(comUserRoleInfos);
            }
        }
        //更新三方于用户关联
        if (CheckUtils.hasInt(param.getThirdId())) {
            ThirdUserInfo thirdUserInfo = thirdUserInfoService.getById(param.getThirdId());
            if (thirdUserInfo != null) {
                thirdUserInfo.setCompanyNo(userInfo.getCompanyNo());
                thirdUserInfo.setUserId(userInfo.getId());
                thirdUserInfo.setEdt(LocalDateTime.now());
                thirdUserInfo.setEip(userInfo.getRegIp());
                thirdUserInfo.setEman(userInfo.getId());
                thirdUserInfoService.updateById(thirdUserInfo);
            }
        }

        //todo:邀请流程是否在注册中
        // 如果有邀请，更新邀请信息状态
        if (CheckUtils.hasInt(param.getInvitationId())) {
//			userInvitationInfoService.update(new UpdateWrapper<UserInvitationInfo>()
//					.eq("id", param.getInvitationId())
//					.set("invitation_state", InviteStateTypeEnum.CONFIRMED.getCode())
//			);
//			// 如果有团队邀请，加入团队
//			if (CheckUtils.hasInt(param.getTeamId())) {
//				if (teamUserInfoService.count(new QueryWrapper<TeamUserInfo>().eq("user_id", userInfo.getId())) < 1) {
//					TeamUserInfo teamUserInfo = new TeamUserInfo();
//					teamUserInfo.setCompanyNo(param.getCompanyNo());
//					teamUserInfo.setTeamId(param.getTeamId());
//					teamUserInfo.setUserId(userInfo.getId());
//					teamUserInfo.addCreateParam(loginUserInfo);
//					teamUserInfo.addEditParam(loginUserInfo);
//					teamUserInfoService.save(teamUserInfo);
//				}
//			}
        }

        //todo:是否需要此流程
        // 如果分销商标识,新建分销商信息
//		if (StrUtil.isNotEmpty(param.getDisFlg()) && BaseConstant.YNEnum.YES.getCode().equals(param.getDisFlg())) {
//			DistributorClientAddParam params = new DistributorClientAddParam();
//			params.setDistributorUserId(userInfo.getId());
//			params.setCompanyNo(userInfo.getCompanyNo());
//			params.setParentDisUserId(referralUserId);
//			params.setClientUserId(userInfo.getId());
//			params.setClientUserIp(param.getRegIp());
//			disRemoteService.add2editDistributor(params);
//		}

        return userInfo;
    }


}

	
	
	
